#include <interfacelib/DirectX/synchronized_dx.h>
#include <interfacelib/window/FontManager.h>

using namespace interfacelib::DirectX;

Synchronized_Update::Synchronized_Update() : m_device ( NULL )
{
	interfacelib::DirectX::InitD3D::getInstance()->setIsDeviceLost();
	LPDIRECT3DDEVICE9 device = interfacelib::DirectX::InitD3D::getInstance()->getDevice();
	device->Clear( 0L, NULL, interfacelib::DirectX::InitD3D::getInstance()->getClearOption(), 0x00000000, 1.0f, 0L );				
	if ( device->BeginScene() != D3D_OK ) return;

	m_device = device;
}

Synchronized_Update::~Synchronized_Update()
{
	if ( !m_device ) return;

	m_device->EndScene();

	HRESULT result = m_device->Present( NULL, NULL, NULL, NULL );
	if ( result == D3D_OK ) return;
	if ( result == D3DERR_DEVICELOST ) interfacelib::DirectX::InitD3D::getInstance()->setIsDeviceLost( true );
}


Synchronized_Sprite::Synchronized_Sprite( DWORD mode )
{
	m_device = interfacelib::DirectX::InitD3D::getInstance()->getDevice();
	m_device->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );

	m_sprite = interfacelib::DirectX::InitD3D::getInstance()->getSprite();
	m_sprite->Begin( mode );
}

Synchronized_Sprite::~Synchronized_Sprite()
{
	m_sprite->Flush();
	m_sprite->End();

	m_device->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
}

Synchronized_Sprite_Rebegin::Synchronized_Sprite_Rebegin( DWORD mode ) : m_mode( mode )
{
	m_device = interfacelib::DirectX::InitD3D::getInstance()->getDevice();
	m_sprite = interfacelib::DirectX::InitD3D::getInstance()->getSprite();
	m_sprite->End();

	m_device->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
}

Synchronized_Sprite_Rebegin::~Synchronized_Sprite_Rebegin()
{
	m_device->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );

	m_sprite->Begin( m_mode );
	
}

Synchronized_DX_VertexBuffer::Synchronized_DX_VertexBuffer( LPDIRECT3DVERTEXBUFFER9 vertexBuffer , int size ) : m_vertexBuffer( vertexBuffer )
{
	vertexBuffer->Lock( 0, size, ( void **)&m_vertices, 0 );
}

Synchronized_DX_VertexBuffer::~Synchronized_DX_VertexBuffer()
{
	m_vertexBuffer->Unlock();
}

void *Synchronized_DX_VertexBuffer::getVertices()
{
	return ( m_vertices ); 
}


Synchronized_DX_TextureRect::Synchronized_DX_TextureRect( LPDIRECT3DTEXTURE9 texture ) : m_texture( texture )
{
	texture->LockRect( 0, &m_d3dLock, NULL,0);//D3DLOCK_DISCARD );
}

Synchronized_DX_TextureRect::~Synchronized_DX_TextureRect()
{
	m_texture->UnlockRect( 0 );
}

void *Synchronized_DX_TextureRect::getBuffer()
{
	return ( m_d3dLock.pBits );
}

int Synchronized_DX_TextureRect::getPitch()
{
	return ( m_d3dLock.Pitch );
}
